<?php

namespace app\bll;

use core\lib\schema\Schema;
use app\validate\UserTable as ValidateUserTable;
use Exception;
use Illuminate\Database\Schema\Blueprint;
use support\Db;

class UserTable
{


    /**
     * 根据ID 查找
     *
     * @param integer $id
     * @return array|null
     */
    public function find(int $id): array|null
    {
        $table = Db::table('frame_user_table')
            ->where('id', '=', $id)
            ->first();
        return $table === null ? [] : get_object_vars($table);
    }

    /**
     * 查询信息表
     *
     * @return array
     */
    public function selectInfoTable(): array
    {
        return Db::table('frame_user_table')
            ->where('regtable', '=', 0)
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }


    /**
     * 根据表名 获取个人信息资料
     *
     * @param integer $uidmap
     * @param string $tablename
     * @param boolean $multiline
     * @return array
     */
    public function userInfoByTableName(
        int $uid,
        string $tablename,
        bool $multiline = false
    ): array {
        if ($multiline) {
            return Db::table($tablename)
                ->where('uid', '=', $uid)
                ->get()
                ->map(function ($value) {
                    return (array)$value;
                })
                ->toArray();
        } else {
            $table = Db::table($tablename)
                ->where('uid', '=', $uid)
                ->first();
            return $table === null ? [] : get_object_vars($table);
        }
    }
    /**
     * 根据表名查找
     *
     * @param string $name
     * @return array|null
     */
    public function findByName(string $name): array|null
    {
        $table = Db::table('frame_user_table')
            ->where('name', '=', $name)
            ->first();
        return $table === null ? [] : get_object_vars($table);
    }


    /**
     * 新增信息表
     *
     * @param array $data
     * @throws Exception
     * @return integer
     */
    public function add(array $data): int
    {

        $ValidateUserTable = new ValidateUserTable();
        if (!$ValidateUserTable->check($data)) {
            throw new Exception($ValidateUserTable->getSimpleError());
        }

        $data['name'] = $data['tablepre'] . $data['name'];
        unset($data['tablepre']);

        if ($this->findByName($data['name'])) {
            throw new Exception('表已经存在');
        }

        $realtablename = getDatabasePrefix() . $data['name'];
        if (Schema::tableExists($realtablename)) {
            throw new Exception('表已经存在');
        }
        Db::schema()->create($data['name'], function (Blueprint $table) {
            $table->id();
            $table->integer('uid');
        });

        return Db::table('frame_user_table')
            ->insertGetId($data);
    }


    /**
     * 修改
     *
     * @param integer $id
     * @param array $data
     * @return integer
     */
    public  function edit(int $id, array $data): int
    {
        $ValidateUserTable = new ValidateUserTable();
        if (!$ValidateUserTable->check($data)) {
            throw new Exception($ValidateUserTable->getSimpleError());
        }

        $data['name'] = $data['tablepre'] . $data['name'];
        unset($data['tablepre']);

        $tableinfo = $this->findByName($data['name']);

        if ($tableinfo && $tableinfo['id'] != $id) {
            throw new Exception('表已经存在');
        }

        $realtablename = getDatabasePrefix() . $data['name'];

        if (Schema::tableExists($realtablename)) {
            throw new Exception('表已经存在');
        }

        $oldtableinfo = $this->find($id);

        if ($oldtableinfo['name'] != $data['name']) {
            //修改表
            Db::schema()->table($oldtableinfo['name'], function (Blueprint $table) use ($data) {
                $table->rename($data['name']);
            });
        }

        return Db::table('frame_user_table')
            ->where('id', '=', $id)
            ->update($data);
    }

    /**
     * 删除
     *
     * @param integer $id
     * @return integer
     */
    public function delete(int $id):int
    {

        //删除表
        $oldtableinfo = $this->find($id);
        Db::schema()->table($oldtableinfo['name'], function (Blueprint $table) {
            $table->drop();
        });

        //删除字段
        Db::table('frame_user_field')
            ->where('tablename', '=', $oldtableinfo['name'])
            ->delete();

        return Db::table('frame_user_table')
            ->where('id', '=', $id)
            ->delete();
    }
}
